package com.hmall.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchService implements ISearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        try {
            //准备request
            SearchRequest request = new SearchRequest("hmall");
            buildBasicQuery(params, request);

            //分页
            request.source().from((params.getPage() - 1) * params.getSize()).size(params.getSize());
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析请求
            SearchHits searchHits = response.getHits();
            //获取总共的数据条数
            long total = searchHits.getTotalHits().value;
            //获取数据
            List<ItemDoc> itemDocList = new ArrayList<>();
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                String source = hit.getSourceAsString();
                ItemDoc itemDoc = JSON.parseObject(source, ItemDoc.class);
                itemDocList.add(itemDoc);
            }
            return new PageDTO<>(total, itemDocList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("hmall");
            request.source().size(0);
            buildBasicQuery(requestParams, request);

            request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20));
            request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(20));
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> map = new HashMap<>(2);
            Aggregations aggregations = response.getAggregations();
            //品牌
            Terms brandAgg = aggregations.get("brandAgg");
            List<String> brandList = new ArrayList<>();
            for (Terms.Bucket bucket : brandAgg.getBuckets()) {
                String key = bucket.getKeyAsString();
                brandList.add(key);
            }
            map.put("brand", brandList);
            //分类
            Terms categoryAgg = aggregations.get("categoryAgg");
            List<String> categoryList = new ArrayList<>();
            for (Terms.Bucket bucket : categoryAgg.getBuckets()) {
                String key = bucket.getKeyAsString();
                categoryList.add(key);
            }
            map.put("category", categoryList);
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void addItemById(Long id) {
        try {
            //查询商品信息
            Item item = itemClient.selectById(id);

            ItemDoc itemDoc = new ItemDoc(item);
            IndexRequest request = new IndexRequest("hmall").id(id.toString());

            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);

            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteItemById(Long id) {
        try {
            DeleteRequest request = new DeleteRequest("hmall").id(id.toString());

            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //构建一个bool查询
    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        //创建bool查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //准备DSL
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        //品牌
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //分类
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        //价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .lte(params.getMaxPrice()*100)
                    .gte(params.getMinPrice()*100));
        }
        //放入request
        request.source().query(boolQuery);
    }
}
